package com.cellulam.log.interaction;

import com.cellulam.framework.core.utils.JacksonUtils;
import com.cellulam.framework.core.rest.RestClient;
import com.cellulam.log.interaction.dto.AccessLogRequest;
import com.cellulam.log.interaction.dto.BizLogRequest;
import com.cellulam.log.interaction.dto.SystemLogRequest;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class LogServiceAgent {

    private final RestClient restClient;

    private final String logServiceHost;

    public LogServiceAgent(String logServiceHost) {
        this.logServiceHost = logServiceHost;
        this.restClient = new RestClient(500);
    }

    public long writeLog(BizLogRequest request) {
        return this.writeLog("/v1/log/biz", request);
    }

    public long writeLog(SystemLogRequest request) {
        return this.writeLog("/v1/log/system", request);
    }

    public long writeLog(AccessLogRequest request) {
        return this.writeLog("/v1/log/access", request);
    }

    private long writeLog(String url, Object request) {
        try {
            return this.restClient.postForResult(logServiceHost + url,
                    request, Long.class);
        } catch (Exception e) {
            log.error("日志写入异常, url: {}, request: {]",
                    url,
                    JacksonUtils.toJson(request),
                    e);
        }
        return -1;
    }

}
